package create.he.common;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;

import cn.hutool.core.lang.Assert;
import create.he.entity.JDBCConfig;
import lombok.extern.slf4j.Slf4j;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**
 * sql 代理类 连接数据库，关闭连接
 * @author heh
 *
 */
@Slf4j
public class SQLProxy implements MethodInterceptor {
	
	private JDBCConfig config;
	
	public SQLProxy(JDBCConfig config) {
		this.config = config;
	}
	public Object getInstance(Class<?> target) {
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(target);
		enhancer.setCallback(this);
		return enhancer.create();
	}
	
	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		JDBCConfig config = this.config;
		// 注册JDBC驱动
		Class.forName(JDBCConfig.JDBC_DRIVER);
		// 打开链接
		Connection conn = DriverManager.getConnection(config.getDB_URL(), config.getUSER(), config.getPASS());
 		// Connection 注入到 实际的查询参数conn当中
		args[1] = conn;
		
		//处理被代理的方法
		Object invokeSuper = proxy.invokeSuper(obj, args);
		
		//关闭连接
		conn.close();
		return invokeSuper;
	}

}
